import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { NziModalService } from 'ng-zorro-iop/modal/nzi-modal.service';
import { NzMessageService } from "ng-zorro-antd";
import { NavHeaderService } from '@global/layout/default/nav-header/nav-header.service';
import { FcsService } from "../../service/fcs.service";
import { ApplicationCreateComponent } from "../create/application-create.component";
import { CommonService } from '../../service/common.service';
import { Region, Group } from '../../shared-component/class/instance';

@Component({
  selector: 'app-application-list',
  templateUrl: './application-list.component.html',
  styleUrls: ['./application-list.component.less']
})
export class ApplicationListComponent implements OnInit {
  isLoading = true;
  totalCount = 0;
  applicationList = [];
  hasInputValue = false;
  searchValue = '';
  errorMsg = '';
  pageSize = 10;
  pageNo = 1;
  regionName='';
  currentRegion:Region={
    regionCode:'',
    regionName:''
  };
  constructor(private fcsService: FcsService,
              private modalService: NziModalService,
              private msgService: NzMessageService,
              private router: Router,
              private navHeaderService: NavHeaderService,
              private commonService: CommonService) { }

  ngOnInit() {
    this.getRegionName();
    this.getApplicationList();
  }

  successFun() {
    this.msgService.success('复制成功!');
  }

  getRegionName(){
    this.commonService.getRegions().subscribe(res => {
      if ( res && res['data']){
         let regions = res['data'];
         let regionId = this.navHeaderService.getCurrentRegion();
         this.regionName = this.commonService.getRegionName(regions,regionId);
         this.currentRegion['regionCode'] = regionId;
         this.currentRegion['regionName'] = this.regionName;
      }
    })
  }

  refresh(){
    // this.searchValue = "";
    this.getApplicationList();
  }

  createApplication() {
    this.modalService.create({
      nzTitle: '创建应用',
      nzMaskClosable: false,
      nzWidth: '7rem',
      nzContent: ApplicationCreateComponent,
      nzComponentParams: { region: this.currentRegion },
      nzOnOk: async createInstance => {
        let isSuccess = await createInstance.submitForm();
        isSuccess && this.getApplicationList();
        return isSuccess;
      },
    });
  }

  editApplication(data) {
    this.modalService.create({
      nzTitle: '编辑应用',
      nzMaskClosable: false,
      nzWidth: '7rem',
      nzContent: ApplicationCreateComponent,
      nzComponentParams: { applicationInstance: data },
      nzOnOk: async createInstance => {
        let isSuccess = await createInstance.submitForm();
        isSuccess && this.getApplicationList();
        return isSuccess;
      },
    });
  }

  deleteApplication(data) {
    this.modalService.delete({
      nzTitle: '删除应用',
      nzContentTitle: `确定删除应用 <em>“${data.displayName}”</em> 吗？`,
      nzOnOk: () => {
        // 返回一个promise对象才可以调用then等函数
        return new Promise((resolve, reject) => {
          this.fcsService.deleteGroup(data.id).subscribe(
            data => {
              if (data && data.code) {
                resolve(false);
                this.msgService.error(data.message || '删除失败！');
              } else {
                this.msgService.success('删除成功！');
                if(this.applicationList.length <= 1){
                  this.pageNo-=1;
                  this.pageNo = this.pageNo <=0 ? 1 : this.pageNo;
                }
                this.getApplicationList();
                resolve(true);
              }
            },
            err => {
              resolve(false);
            });
        });
      },
      nzCancelText: '取消',
      nzOnCancel: () => { },
    });
  }
  getApplicationList() {
    this.isLoading = true;
    this.hasInputValue = this.searchValue != '';
    this.fcsService.getGroupPaginationList(this.pageNo,this.pageSize,this.searchValue).subscribe(res => {
      if(res && res.totalCount != undefined){
        this.totalCount = res.totalCount;
        this.pageNo = res.pageNo;
        this.pageSize = res.pageSize;
        if(res.data && res.data.length >= 0){
          this.applicationList = res.data;
        }
      }
      if (this.totalCount > 0 && this.applicationList ==[]) {
        this.pageNo = Math.floor(this.totalCount / this.pageSize);
        this.getApplicationList();
      }
      this.isLoading = false;
    },error => {
      this.errorMsg = error;
      this.isLoading = false;
    })
  }

  trackById(index: number, data: Group): string {
    return data.id;
  }

  createFunction(applicationId){
    this.router.navigate(['/fcs-manage/function/create'],{queryParams:{applicationId:applicationId,regionCode:this.currentRegion.regionCode,regionName:this.currentRegion.regionName}});
  }

}
